package org.appmon.core.agent.loader;

import java.lang.management.ManagementFactory;

import com.sun.tools.attach.VirtualMachine;


public class PostJvmAgentLoader {
	
	
	 
	 private static final String jarFilePath=LoadUtils.extractJarUrlLocation();	 
	 public static boolean isAgentLoaded;
	
	
	    public static void loadAgent() {
	    	System.out.println("JAR-PATH : "+jarFilePath);
	     
	        String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
	        int p = nameOfRunningVM.indexOf('@');
	        String pid = nameOfRunningVM.substring(0, p);
	        System.out.println("JVM Agent Loading Started.....");
	        try {	            
	            synchronized(PostJvmAgentLoader.class){
	         //   	System.out.println("Agent Hash : "+AgentTracker.getInstance().hashCode());
	            if(!AgentTracker.getInstance().isAgentLoaded()){
	         //   	System.out.println("Agent Load : "+AgentTracker.getInstance().isAgentLoaded());
	            	VirtualMachine vm = VirtualMachine.attach(pid);
		            vm.loadAgent(jarFilePath, "");
		            AgentTracker.getInstance().setAgentLoaded(true);
		            vm.detach();
	            }
	            }
	        } catch (Exception e) {
	            throw new RuntimeException(e);
	        }
	        System.out.println("Agent Loading Completed ...");
	    }

	 

}
